<template>
  <el-dialog :model-value="dialogVisible" title="导入数据" width="30%" align-center @closed="dialogVisible = false">
    <el-upload
      ref="refUpload"
      drag
      accept=".xls, .xlsx"
      :auto-upload="false"
      :action="uploadAction"
      :headers="headers"
      @change="handleChange"
      @success="handleSuccess"
      @error="handleError"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text"> 将Excel文件拖动至此或者<em>点击上传</em> </div>
      <template #tip>
        <div class="el-upload__tip"> Excel文件大小不能超过10MB </div>
      </template>
    </el-upload>
    <template #footer>
      <el-row>
        <el-col :span="12" style="text-align: left">
          <el-link :underline="false" @click="handleDownloadTemp"><span class="temp">下载模版文件</span></el-link>
        </el-col>
        <el-col :span="12">
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">关 闭</el-button>
            <el-button type="primary" @click="handleImport">导 入</el-button>
          </span>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
  <el-button v-bind="$attrs" type="primary" :icon="Upload" @click="dialogVisible = true"> 导入 </el-button>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElDialog, ElUpload, ElMessage } from 'element-plus'
import type { UploadInstance, UploadFiles, UploadFile } from 'element-plus'
import { Upload, UploadFilled } from '@element-plus/icons-vue'
import { env, header } from '@/utils'
import { download } from '@/api/request'

const props = withDefaults(defineProps<{ action: string; template: string }>(), { action: '', template: '' })
const emits = defineEmits(['ok', 'error'])

const uploadAction = computed(() => (props.action ? `${env.API_DOMAIN}${props.action}` : ''))
const headers = computed(() => header.getAuthorization())

const refUpload = ref<UploadInstance>()

const dialogVisible = ref(false)

const handleImport = () => {
  refUpload.value!.submit()
}
const handleChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  if (uploadFiles.length > 1) {
    uploadFiles.splice(0, 1)
  }
}
const handleSuccess = (resp: any, uploadFile: UploadFile) => {
  emits('ok', { resp, uploadFile })
  if (resp.success) {
    download({ url: `/file/temp/object/download?objectName=${encodeURI(resp.data)}` })
    dialogVisible.value = false
  } else {
    ElMessage.error(resp.message)
  }
}
const handleError = (error: Error, uploadFile: UploadFile) => {
  emits('error', { error, uploadFile })
}
const handleDownloadTemp = () => {
  download({ url: `/template/download/${props.template}` })
}
</script>

<style lang="scss" scoped>
.temp {
  color: $--color-primary;
}
</style>
